package com.twu.biblioteca;

import com.twu.biblioteca.Goods.Goods;
import com.twu.biblioteca.User.User;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.twu.biblioteca.Println.SUCCEED_BORROW_BOOK;

public class Shelf {
    public static final String SEPARATOR = " ";
    private HashMap<Goods, User> map = new LinkedHashMap<Goods, User>();

    public HashMap<Goods, User> getMap() {
        return map;
    }

    public void showAllGoods() {
        Println.println(Println.OUTPUT_BOOK_LIST);
        String goods = "";
        Iterator<Map.Entry<Goods, User>> entries = map.entrySet().iterator();
        int i=0;
        while (entries.hasNext()){
            Map.Entry<Goods, User> entry = entries.next();
            String temp = (i + 1) + "." + entry.getKey().getName() + SEPARATOR;
            goods += temp;
            i++;
        }
        Println.println(goods);
    }

    public void add(Goods goods) {
        map.put(goods, null);
    }

    public Goods findGoodsByName(String goodsName){
        Iterator<Map.Entry<Goods, User>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            Goods goods = iterator.next().getKey();
            if(goods.equals(new Goods(goodsName))){
                return goods;
            }
        }
        return null ;
    }

    public boolean isExist(String goodsName) {
        return map.containsKey(new Goods(goodsName));
    }

    public void setBorrower(String goodsName, User borrower) {
        if(isExist(goodsName)){
            map.put(findGoodsByName(goodsName), borrower);
        }
        Println.println(SUCCEED_BORROW_BOOK);
    }

    public User getBorrower(String bookName) {
        return map.get(findGoodsByName(bookName));
    }

    public boolean isBorrowed(String goodsName) {
        if (map.get(new Goods(goodsName))==null) {
            return false;
        }
        return true;
    }

    public void returnGoods(String bookName){
        if(findGoodsByName(bookName)!=null){
            map.put(findGoodsByName(bookName), null);
        }
    }


}
